package cn.wipace.actionlib.network;

import cn.wipace.actionlib.config.Config;
import cn.wipace.actionlib.model.Result;
import cn.wipace.actionlib.model.UploadResult;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/5/22.
 */

public class ApiService {

    private Api mApi;
    private static ApiService mInstance;

    private ApiService() {
        mApi = getClient().create(Api.class);
    }

    public static ApiService getInstance() {
        if (mInstance == null) {
            mInstance = new ApiService();
        }
        return mInstance;
    }

    /**
     * 设置网络请求客户端
     *
     * @return
     */
    public Retrofit getClient() {
        return new Retrofit.Builder()
                .baseUrl(Config.HOST)
                .addConverterFactory(GsonConverterFactory.create())//gson适配器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//RxJava适配器
                .build();
    }

    /**
     * 获取分页meizhi数据
     */
    public void getUserScoreData(HttpResultListener<Result> listener, final long uid) {
        mApi.getUserScoreData(uid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpResultSubscriber<Result>(listener));
    }

    public void uploadUserScoreData(UploadResult score, HttpResultListener<Result> listener) {
        mApi.uploadUserScoreData(score)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpResultSubscriber<Result>(listener));
    }

    /**
     * 封装网络访问的返回
     *
     * @param <T>
     */
    private static class HttpResultSubscriber<T> extends Subscriber<T> {
        private HttpResultListener<T> mListener;

        public HttpResultSubscriber(HttpResultListener<T> listener) {
            mListener = listener;
        }

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            if (mListener != null) {
                mListener.onError(e);
            }
        }

        @Override
        public void onNext(T t) {
            if (mListener != null) {
                mListener.onSuccess(t);
            }

        }
    }


}
